﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using CCF20Model.ModelBase;
using WiseLink.RDS.Resource;

namespace CCF20Model
{
    public class FaultModel : ModelBaseClass
    {
        
        
        public FaultModel(CCF20Entities ccf20Ent):base(ccf20Ent)
        {
            
            
        }
        public DateTime GetLastCrashTime()
        {
            CCF20Entities ccf20Entities = new CCF20Entities();
            using (ccf20Entities)
            {
                Fault lastCrash = ccf20Entities.Faults.Where(f => f.FaultType == WiseLinkRDSStatus.Fault_Type_Urgent).OrderByDescending(f => f.HappenDate).FirstOrDefault();
                if (lastCrash != null)
                {
                    return lastCrash.HappenDate;
                }
                else
                {
                    //if there is not crash data before. then try from last 24 hours.
                    return new DateTime(2011, 1, 1);
                    //return (DateTime.Now - new TimeSpan(24, 0, 0));
                }
            }
        }
        public Vehicle GetVehicleBySimNumber(Fault f)
        {
            Vehicle vehicle = ccf20Entities.Vehicles.Where(v => v.Devices.Count(d => d.IDCSimNumber == f.IDCSimNumber && 
                                                                                     d.IsRegistered ==true) == 1).FirstOrDefault();
            if (vehicle == null)
            {
                f.IsActive = false;
                f.IsConfirmed = false;
                f.CloseReason = "未找到车辆";
                LoggerHelper.LogZICDebug(f, string.Format("没有找到SIM卡号为{0},并且已经注册成功的车辆", f.IDCSimNumber));
                return null;
            }
            else
            {
                return vehicle;
            }
        }
        public int GetAnchiID()
        {
            //to always get the latest anchiid

            CCF20Entities ccf20Entities = new CCF20Entities();
            using (ccf20Entities)
            {
                int? maxID = ccf20Entities.Faults.Where(f => f.FaultType == WiseLinkRDSStatus.Fault_Type_Fault).Max(f => f.AnchiID);
                if (maxID == null)
                {
                    return 0;
                }
                else
                {
                    return (int)maxID;
                }
            }
        }

    
        
        public void GetCustomizedCode(Fault fault)
        {
            CustomizedTroubleCode customizedCode = ccf20Entities.CustomizedTroubleCodes.Where(c => c.Code == fault.Code).FirstOrDefault();
            if (customizedCode != null)
            {
                fault.CodeDescription = customizedCode.CodeDescription;
            }
        }
        public void AddDirectTroubleCode(Fault skipCode)
        {
            CustomizedTroubleCode ctc = ccf20Entities.CustomizedTroubleCodes.Where(c => c.Code == skipCode.Code &&
                                                                                        c.CodeVersion == skipCode.CodeVersion &&
                                                                                         c.VehicleTypeID == skipCode.Vehicle.VehicleTypeID).FirstOrDefault();
            if (ctc == null)
            {
                ctc = new CustomizedTroubleCode();
                ccf20Entities.CustomizedTroubleCodes.AddObject(ctc);
            }
            ctc.Code = skipCode.Code;
            ctc.FaultInfo = skipCode.FaultInfo;
            ctc.CodeDescription = skipCode.CodeDescription;
            ctc.CodeVersion = skipCode.CodeVersion;
            ctc.CodeType = skipCode.CodeType;
            ctc.OperationType = "直通车";
            // 目前ZIC是通过 CodeType 来设置等级如 AB /CD.
            //对于RDS使用Priority数字来区分等级 0，1 直通车， 2，3 不变， 4，5 人工排除
            ctc.Priority = 1;
            ctc.IsCustomized = true;
            Vehicle vehicle = ccf20Entities.Vehicles.Where(v => v.VehicleID == skipCode.VehicleID).FirstOrDefault();
            if (vehicle != null)
            {
                ctc.VehicleType = vehicle.VehicleType;
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("[直通车] 但无法找到相应车型 Fault={0},VehicleID={1},VehicleTypeID={2}",
                                               skipCode.Code,
                                               skipCode.Vehicle.VehicleID,
                                               skipCode.Vehicle.VehicleTypeID));
                return;
            }
            Fault myFault = ccf20Entities.Faults.Where(f => f.FaultID == skipCode.FaultID).FirstOrDefault();
            if (myFault != null)
            {
                myFault.IsConfirmed = true;
                myFault.CloseReason = "直通车";
                LoggerHelper.LogCCF20(string.Format("将故障码{0} 车型{1}-{2}-{3}-{4} 设置为直通车",
                                                myFault.Code,
                                                vehicle.VehicleType.Manufacture,
                                                vehicle.VehicleType.Model,
                                                vehicle.VehicleType.EngineType,
                                                vehicle.VehicleType.ModelYear));

            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("[设置直通车] 无法找到故障码 FaultID={0}, Code={1} 车型{2}-{3}-{4}-{5} ",
                                                skipCode.FaultID,
                                                skipCode.Code,
                                                vehicle.VehicleType.Manufacture,
                                                vehicle.VehicleType.Model,
                                                vehicle.VehicleType.EngineType,
                                                vehicle.VehicleType.ModelYear));
                return;
            }
            ccf20Entities.SaveChanges();

        }
        public void AddSkipTroubleCode(Fault skipCode)
        {
            CustomizedTroubleCode ctc = ccf20Entities.CustomizedTroubleCodes.Where(c => c.Code == skipCode.Code && 
                                                                                    c.CodeVersion == skipCode.CodeVersion &&
                                                                                    c.VehicleTypeID == skipCode.Vehicle.VehicleTypeID).FirstOrDefault();
            if (ctc == null)
            {
                ctc = new CustomizedTroubleCode();
                ccf20Entities.CustomizedTroubleCodes.AddObject(ctc);
            }
            ctc.Code = skipCode.Code;
            ctc.FaultInfo = skipCode.FaultInfo;
            ctc.CodeDescription = skipCode.CodeDescription;
            ctc.CodeVersion = skipCode.CodeVersion;
            ctc.OperationType = "人工排除";
            ctc.CodeType = skipCode.CodeType;
            // 目前ZIC是通过 CodeType 来设置等级如 AB /CD.
            //对于RDS使用Priority数字来区分等级 0，1 直通车， 2，3 不变， 4，5 人工排除
            ctc.Priority = 5;
            ctc.IsCustomized = true;
            Vehicle vehicle = ccf20Entities.Vehicles.Where(v => v.VehicleID == skipCode.VehicleID).FirstOrDefault();
            if (vehicle != null)
            {
                ctc.VehicleType = vehicle.VehicleType;
                ctc.VehicleTypeID = vehicle.VehicleType.VehicleTypeID;
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("[排除偶发故障] 但无法找到相应车型 Fault={0},VehicleID={1},VehicleTypeID={2}]",
                                                skipCode.Code,
                                                skipCode.Vehicle.VehicleID,
                                                skipCode.Vehicle.VehicleTypeID));
            }
            //
            IEnumerable<Fault> myFaults = ccf20Entities.Faults.Where(f => f.IsActive == true &&
                                                                            f.Code == ctc.Code &&
                                                                            f.CodeVersion == ctc.CodeVersion &&
                                                                            f.Vehicle.VehicleTypeID == ctc.VehicleTypeID);
            foreach (Fault myFault in myFaults)
            {
                myFault.IsActive = false;
                myFault.CloseDate = DateTime.Now;
                myFault.IsConfirmed = true;
                myFault.PreviousCloseReason = myFault.CloseReason;
                myFault.CloseReason = "人工排除";
                LoggerHelper.LogCCF20(string.Format("[人工排除偶发故障] Fault={0},VehicleID={1},VehicleTypeID={2}]",
                                                skipCode.Code,
                                                skipCode.Vehicle.VehicleID,
                                                skipCode.Vehicle.VehicleTypeID));
            }
            ccf20Entities.SaveChanges();
        }
        public void ConfirmTroubleCode(Fault confirmCode)
        {
            Fault fault = ccf20Entities.Faults.Where(f => f.FaultID == confirmCode.FaultID).FirstOrDefault();
            if (fault != null)
            {
                fault.IsConfirmed = true;
                fault.CloseReason = "已经确认";
                ccf20Entities.SaveChanges();
            }
        }
        public string GetZICUrl()
        {
            CompanyProfile profile = ccf20Entities.CompanyProfiles.FirstOrDefault();
            string url;
            if (profile != null)
            {
                url = profile.ZICUrl;
            }
            else
            {
                url = "http://218.249.201.46:8899/zic/zicwebservice.asmx";
            }
            //EndpointAddress endpoint;
            //try
            //{
            //    endpoint = new EndpointAddress(url);
            //}
            //catch (Exception ex)
            //{
            //    endpoint = new EndpointAddress("http://218.249.201.46:8899/zic/zicwebservice.asmx");
            //}
            return url;
        }
        public void UpdateZICInfo(DateTime lastAccessTime,bool IsAvailable)
        {
            CompanyProfile profile = ccf20Entities.CompanyProfiles.FirstOrDefault();
            profile.ZICAvailable = IsAvailable;
            if (IsAvailable)
            {
                profile.ZICUpdateTime = lastAccessTime;
            }
            ccf20Entities.SaveChanges();
            
        }
        public void GetZICInfo(out DateTime lastAccessTime, out bool IsAvailable)
        {
            CompanyProfile profile = ccf20Entities.CompanyProfiles.FirstOrDefault();
            IsAvailable = profile.ZICAvailable ?? true ;
            lastAccessTime = profile.ZICUpdateTime ?? DateTime.Now ;
        }
        public LoginInfo GetLoginInfo()
        {
            CompanyProfile profile = ccf20Entities.CompanyProfiles.FirstOrDefault();
            LoginInfo login = new LoginInfo();
            if (profile != null)
            {
                login.IDSName = profile.LoginName;
                login.IDSPassword = profile.LoginPassword;
            }
            else
            {
                throw new ArgumentNullException("There is no profile found in the database");
            }
            return login;
        }

        public void CustomizeCodeDescription(int vehicleID,string newValue,Fault fault )
        {
            Vehicle vehicle = ccf20Entities.Vehicles.Where(v => v.VehicleID == vehicleID).FirstOrDefault();
            if (vehicle == null) return;

            CustomizedTroubleCode ctc = ccf20Entities.CustomizedTroubleCodes.Where(c => c.Code == fault.Code && c.VehicleTypeID == vehicle.VehicleTypeID).FirstOrDefault();
            if (ctc == null)
            {
                ctc = new CustomizedTroubleCode();
                ccf20Entities.CustomizedTroubleCodes.AddObject(ctc);
                ctc.Code = fault.Code;
                // 目前ZIC是通过 CodeType 来设置等级如 AB /CD.
                //对于RDS使用数字来区分等级 0，1 直通车， 2，3 不变， 4，5 人工排除
                ctc.Priority = 3;// fault.Priority; 
                ctc.CodeVersion = fault.CodeVersion;
                ctc.CodeType = fault.CodeType;
                ctc.OperationType = "定制";
                ctc.IsCustomized = true;
                ctc.VehicleTypeID = vehicle.VehicleTypeID;

            }
            ctc.CodeDescription = newValue;
            ccf20Entities.SaveChanges();

        }
        public void CustomizeCodePriority(int vehicleID, int newValue, Fault fault)
        {
            Vehicle vehicle = ccf20Entities.Vehicles.Where(v => v.VehicleID == vehicleID).FirstOrDefault();
            if (vehicle == null) return;

            CustomizedTroubleCode ctc = ccf20Entities.CustomizedTroubleCodes.Where(c => c.Code == fault.Code && c.VehicleTypeID == vehicle.VehicleTypeID).FirstOrDefault();
            if (ctc == null)
            {
                ctc = new CustomizedTroubleCode();
                ccf20Entities.CustomizedTroubleCodes.AddObject(ctc);
                ctc.Code = fault.Code;
                ctc.CodeDescription = fault.CodeDescription;    
                ctc.CodeVersion = fault.CodeVersion;
                ctc.CodeType = fault.CodeType;
                ctc.OperationType = "定制";
                ctc.IsCustomized = true;
                ctc.VehicleTypeID = vehicle.VehicleTypeID;

            }
            ctc.Priority = (short)newValue;
            ccf20Entities.SaveChanges();

        }
        public IQueryable<Fault> GetFaultQuery()
        {
            var query = from f in ccf20Entities.Faults
                        where f.FaultType != WiseLinkRDSStatus.Fault_Type_Maintenance && f.CloseReason != "重复故障"
                        orderby f.HappenDate descending
                        select f;
            return query;
        }
        public IQueryable<VehicleMaintenanceHistory> GetMaintenanceQuery()
        {
            var query = from m in ccf20Entities.VehicleMaintenanceHistories
                        orderby m.CloseDate descending
                        select m;
            return query;
        }
        
    }

    public class LoginInfo
    {
        public string IDSName { get; set; }
        public string IDSPassword { get; set; }
    }
    
}
